package ch.fhnw.qualiscan.application.pages.tabs;


import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.modals.NextStageModal;
import ch.fhnw.qualiscan.application.pages.EditSurvey;
import ch.fhnw.qualiscan.core.db.pojos.Domain;
import ch.fhnw.qualiscan.core.db.pojos.DomainText;
import ch.fhnw.qualiscan.core.db.pojos.Language;
import ch.fhnw.qualiscan.core.db.pojos.Question;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.db.pojos.User;

import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.BaseTheme;

import eu.livotov.tpt.i18n.TM;

@SuppressWarnings("serial")
public class EditSurveyTab1Coordinator extends VerticalLayout {
	
	public EditSurvey editSurvey;
	public Label currentStage;
	
	private Panel panel1;
	private Panel panel2;
	private Panel panel3;
	
	public int stage = -1;
	
	public EditSurveyTab1Coordinator(EditSurvey editSurvey) {
		this.editSurvey = editSurvey;
		buildTab();
	}
	
	public void buildTab() {
		this.removeAllComponents();
		this.addComponent(buildPanel1());
		//this.addComponent(buildPanel2());
		this.addComponent(buildPanel3());
	}
	
	public Panel buildPanel1() {
		panel1 = new Panel();
		panel1.addComponent(editSurvey.textHelper.h3(TM.get("editsurvey.tab1.stagepanel.title")));
		
		VerticalLayout spacer = new VerticalLayout();
		spacer.setHeight("15px");
		
		panel1.addComponent(spacer);
		panel1.addComponent(stageBox());
	
		return panel1;
	}
	
	public Panel buildPanel2() {
		panel2 = new Panel();
		panel2.addComponent(editSurvey.textHelper.h3(TM.get("editsurvey.tab1.ownprogresspanel.title")));
		
		CssLayout spacer = new CssLayout();
		spacer.setHeight("15px");
		spacer.setWidth("100%");
		panel2.addComponent(spacer);
		
		boolean isSurveyFinished = true;
		CssLayout surveyFinishedWrap = new CssLayout();
		surveyFinishedWrap.setVisible(false);
		surveyFinishedWrap.setMargin(true);
		surveyFinishedWrap.setWidth("800px");
		surveyFinishedWrap.setStyleName("box-ok");
		
		Label surveyFinished = new Label();
		surveyFinishedWrap.addComponent(surveyFinished);

		panel2.addComponent(surveyFinishedWrap);
		
		Language l = editSurvey.userSession.getLanguage();	
		Iterator it = editSurvey.currentSurvey.getDomains().iterator();	
		while(it.hasNext()) {

			Domain d = (Domain)it.next();
			DomainText dt = editSurvey.domainModel.getDomainText(d, l);
			
			int nQuestions = 0;
			Iterator<Question> questionIterator= d.getQuestions().iterator();
			while (questionIterator.hasNext()) {
				Question q = questionIterator.next();
				if (q.getSubquestions().size() > 0) {
					nQuestions = nQuestions + q.getSubquestions().size();
				}
				else {
					nQuestions++;
				}
			}
			
			int totalAnswers = editSurvey.domainModel.getNumberOfAnswersForSurAndDomain(editSurvey.sur, d);
			float progress = (float)totalAnswers/(float)nQuestions;
			if (progress != 1.0) {
				isSurveyFinished = false;
			}

			// container
			HorizontalLayout container = new HorizontalLayout();
			container.setSpacing(true);
			container.setMargin(true, false, false, false);
			
			//Title
			Label domainTitle = editSurvey.textHelper.span(dt.getText());
			domainTitle.setWidth("300px");
			
			//Indicator
			ProgressIndicator progressIndicator = new ProgressIndicator();
			progressIndicator.setValue(progress);
			progressIndicator.setWidth("");
			progressIndicator.setPollingInterval(180000);
			
			//Fill in Button
			Button actionButton = new Button(TM.get("editsurvey.fillout"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					Domain domain = (Domain)event.getButton().getData();
					editSurvey.urlLib.setFragment("FillOut/"+editSurvey.sur.getId()+"/"+domain.getId()+"/", true);
				}
			});
			actionButton.setData(d);
			actionButton.setIcon(Config.ICON_EDIT);
			
			if(editSurvey.currentSurvey.getStage().getId() == Config.STAGE_EVALUATION) {
				actionButton.setEnabled(false);
			}
			
			container.addComponent(domainTitle);
			container.addComponent(progressIndicator);
			
			container.addComponent(actionButton);
			container.setComponentAlignment(actionButton, Alignment.MIDDLE_CENTER);
			
			container.setComponentAlignment(domainTitle, Alignment.MIDDLE_CENTER);
			container.setComponentAlignment(progressIndicator, Alignment.MIDDLE_CENTER);

			panel2.addComponent(container);
		}
		
		if (isSurveyFinished) {
			if(editSurvey.currentSurvey.getStage().getId() == Config.STAGE_SURVEY) {
				surveyFinished.setValue(TM.get("editsurvey.tab1.surveyfinished"));
				surveyFinishedWrap.setVisible(true);
			} else {
				surveyFinished.setValue(TM.get("editsurvey.tab1.surveyfinished.results"));
				surveyFinishedWrap.setVisible(true);
			}
		}
	
		return panel2;
	}
	
	public Panel buildPanel3() {
		panel3 = new Panel();
		panel3.addComponent(editSurvey.textHelper.h3(TM.get("editsurvey.tab1.progresspanel.title")));
		
		//Progress Panel
		List<SurveyUserRole> surList = editSurvey.surveyModel.getParticipantsOfSurvey(editSurvey.currentSurvey);
		Language l = editSurvey.userSession.getLanguage();	
		Iterator it = editSurvey.currentSurvey.getDomains().iterator();	
		while(it.hasNext()) {
			Domain d = (Domain)it.next();
			DomainText dt = editSurvey.domainModel.getDomainText(d, l);
			
			int totalAnswers = 0;
			for (int i = 0; i < surList.size(); i++) {
				totalAnswers = totalAnswers + editSurvey.domainModel.getNumberOfAnswersForSurAndDomain(surList.get(i), d);
			}
			
			int nQuestions = 0;
			Iterator<Question> questionIterator= d.getQuestions().iterator();
			while (questionIterator.hasNext()) {
				Question q = questionIterator.next();
				if (q.getSubquestions().size() > 0) {
					nQuestions = nQuestions + q.getSubquestions().size();
				}
				else {
					nQuestions++;
				}
			}
			int totalQuestions = nQuestions * surList.size();
			float progress = (float)totalAnswers/(float)totalQuestions;

			// container
			HorizontalLayout container = new HorizontalLayout();
			container.setSpacing(true);
			container.setMargin(true, false, false, false);
			
			//Title
			Label domainTitle = editSurvey.textHelper.span(dt.getText());
			domainTitle.setWidth("300px");
			
			//Indicator
			ProgressIndicator progressIndicator = new ProgressIndicator();
			progressIndicator.setValue(progress);
			progressIndicator.setWidth("");
			progressIndicator.setPollingInterval(180000);
			
			
			container.addComponent(domainTitle);
			container.addComponent(progressIndicator);
			
			container.setComponentAlignment(domainTitle, Alignment.MIDDLE_CENTER);
			container.setComponentAlignment(progressIndicator, Alignment.MIDDLE_CENTER);
			
			panel3.addComponent(container);
		}
		
		return panel3;
	}
	
	public VerticalLayout stageBox() {
		
		//persist survey
		editSurvey.currentSurvey.getStage();
		String currentStageTitle = editSurvey.surveyModel.getStageText(editSurvey.currentSurvey.getStage(), editSurvey.sessionHelper.getUserSession().getLanguage()).getTitle();
		Label currentStageText = editSurvey.textHelper.p(TM.get("editsurvey.tab1.stagepanel.currentstage", currentStageTitle));
		Label nextStageTextLabel = null;
		
		VerticalLayout stageBox = new VerticalLayout();
		stageBox.setMargin(false, true, true, true);
		stageBox.setSpacing(true);
		stageBox.setStyleName("stageBox");
		stageBox.setWidth("800px");
		
		if (editSurvey.surveyModel.isNextStage(editSurvey.currentSurvey.getStage())) {
			String nextStageText = editSurvey.stageHelper.getNextStageText(editSurvey.currentSurvey.getStage()).getTitle();
			nextStageTextLabel = editSurvey.textHelper.p(TM.get("editsurvey.tab1.stagepanel.nextstage", nextStageText));
		}
		else {
			nextStageTextLabel = new Label(TM.get("editsurvey.tab1.stagepanel.nonextstage"));
		}
		
		Label stageStatus = null;
		Label stageDesc = null;
		Button nextStageButton = null;
		Button evaluationLink = null;
		
		int status = editSurvey.stageHelper.getState(editSurvey.currentSurvey);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		// survey cannot be terminated
		if(status == 1) {
			stageBox.setStyleName("box-warning");
			stageStatus = editSurvey.textHelper.h4(TM.get("state.1.title"));
			stageDesc = editSurvey.textHelper.p(TM.get("state.1.desc", df.format(editSurvey.currentSurvey.getCompletiondate()).toString()));
			nextStageButton = new Button(TM.get("state.1.switch"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					editSurvey.openModal(new NextStageModal(editSurvey.currentSurvey, (EditSurveyTab1Coordinator) event.getButton().getData(), event));
					editSurvey.buildLayout();
				}
			});
			nextStageButton.setIcon(Config.ICON_GO_SQUARE);
			stage = 1;
			nextStageButton.setData(this);
			nextStageButton.setEnabled(false);
		}  
		// survey can be terminated
		else if(status == 2) {
			stageBox.setStyleName("box-ok");
			stageStatus = editSurvey.textHelper.h4(TM.get("state.2.title"));
			stageDesc = editSurvey.textHelper.p(TM.get("state.2.desc", df.format(editSurvey.currentSurvey.getCompletiondate()).toString()));
			nextStageButton = new Button(TM.get("state.2.switch"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					editSurvey.openModal(new NextStageModal(editSurvey.currentSurvey, (EditSurveyTab1Coordinator) event.getButton().getData(), event));
				}
			});
			nextStageButton.setIcon(Config.ICON_GO_SQUARE);
			stage = 2;
			nextStageButton.setData(this);
		}
		// survey is terminated
		else if(status == 3) {
			stageBox.setStyleName("box-warning");
			stageStatus = editSurvey.textHelper.h4(TM.get("state.3.title"));
			stageDesc = editSurvey.textHelper.p(TM.get("state.3.desc"));
			
			evaluationLink = new Button(TM.get("goto.evaluation"));
			evaluationLink.setStyleName(BaseTheme.BUTTON_LINK);
			evaluationLink.addListener(new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					editSurvey.urlLib.setFragment("Evaluation/0/"+ editSurvey.sur.getId() + "/", true);
				}
			});

			nextStageButton = new Button(TM.get("state.3.switch"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					editSurvey.openModal(new NextStageModal(editSurvey.currentSurvey, (EditSurveyTab1Coordinator) event.getButton().getData(), event));
				}
			});
			nextStageButton.setIcon(Config.ICON_GO_SQUARE);
			stage = 3;
			nextStageButton.setData(this);
		}
		// survey is closed
		else if(status == 4) {
			stageBox.setStyleName("box-ok");
			stageStatus = editSurvey.textHelper.h4(TM.get("state.4.title"));
			stageDesc = editSurvey.textHelper.p(TM.get("state.4.desc"));
			
			evaluationLink = new Button(TM.get("goto.evaluation"));
			evaluationLink.setStyleName(BaseTheme.BUTTON_LINK);
			evaluationLink.addListener(new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					editSurvey.urlLib.setFragment("Evaluation/0/"+ editSurvey.sur.getId() + "/", true);
				}
			});
		}
		
		stageBox.addComponent(stageStatus);
		stageBox.addComponent(stageDesc);
		
		if(status == 3) {
			stageBox.addComponent(evaluationLink);
			HorizontalLayout buttonWrapper = new HorizontalLayout();
			buttonWrapper.setMargin(true, false, false, false);
			buttonWrapper.addComponent(nextStageButton);
			stageBox.addComponent(buttonWrapper);
		}
		if (status == 4) {
			stageBox.addComponent(evaluationLink);
		}
		
		if(status == 1 || status == 2) {
			stageBox.addComponent(nextStageButton);
		}
		
		return stageBox;
	}
	
	
}	
